<?php

namespace App\Admin\Forms;

use App\Models\Chapter;
use Carbon\Carbon;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Exception;
use Illuminate\Support\Facades\DB;

class ReplicateChapterForm extends Form implements LazyRenderable
{
    use LazyWidget;

    public function handle(array $input): JsonResponse
    {
        try {
            DB::transaction(function () use ($input) {
                $model = Chapter::find($this->payload['chapter_id']);

                $new = $model->replicate();

                $new->title = $input['title'];
                $new->start_at = $input['start_at'];
                $new->end_at = $input['end_at'];
                $new->save();

                foreach ($model->sponsors as $sponsor) {
                    $sponsor = $sponsor->toArray();
                    unset($sponsor['id']);
                    $new->sponsors()->create($sponsor);
                }
            });

            return $this->response()->success('场次复制完成')->refresh();
        } catch (Exception) {
            return $this->response()->error('场次复制出错了')->refresh();
        }
    }

    public function form(): void
    {
        $this->text('title', '新场次名称')
            ->required();
        $this->datetimeRange('start_at', 'end_at', '新起始时间')
            ->required();
    }

    public function default(): array
    {
        $chapter = Chapter::find($this->payload['chapter_id']);

        return [
            'title' => $chapter->title,
            'start_at' => Carbon::today()->addHours(12),
            'end_at' => Carbon::today()->addWeek()->addHours(12),
        ];
    }
}
